//
//  ViewController.swift
//  SocketIOSwiftDemo
//
//  Created by YangWei on 2021/6/20.
//  Copyright © 2021 YangWei. All rights reserved.
//

import UIKit
import SocketIO

let socketManager = SocketManager(socketURL: URL(string: "http://127.0.0.1:3000")!, config: [.log(true), .compress, .version(.two)])

class ViewController: UIViewController {

    var button: UIButton!
    var socket: SocketIOClient!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        initUI()
        initData()
    }
    
    func initUI() {
        button = UIButton(type: .custom)
        button.frame = CGRect(x: 100, y: 100, width:100 , height: 60)
        button.setTitle("Send", for: .normal)
        button.backgroundColor = UIColor.orange
        button.addTarget(self, action:#selector(sendMsg), for: .touchUpInside)
        
        self.view.addSubview(button)
    }
    
    func initData() {
        
        socket = socketManager.defaultSocket
        
        socket.on(clientEvent: .connect) {data, ack in
            print("socket connected")
        }
        
        socket.on("currentAmount") {data, ack in
            guard let cur = data[0] as? Double else { return }

            self.socket.emitWithAck("canUpdate", cur).timingOut(after: 0) {data in
                if data.first as? String ?? "passed" == SocketAckStatus.noAck {
                    // Handle ack timeout
                }

                self.socket.emit("update", ["amount": cur + 2.50])
            }

            ack.with("Got your currentAmount", "dude")
        }

        socket.connect()
    }
    
    @objc func sendMsg() {
        self.socket.emit("send", "hello")
    }
}

